<?php
class Backend_Videoblock_Controller extends Backend_Controller_Crud_Vc
{

	public function indexAction()
	{
		parent::indexAction();
		$this->_resource->addJs('/js/app/system/RelatedGridPanel.js' , 1);
	}

	/**
	 * Get pages
	 */
	public function pagelistAction()
	{
		$pModel = Model_Page::getInstance();
		$list = $pModel->getListVc(false , false , false , array(
				'id' => 'id' , 
				'title' => 'menu_title'
		));
		array_unshift($list , array(
				'id' => 0 , 
				'title' => 'Default list'
		));
		Response::jsonSuccess($list);
	}

	/**
	 * (non-PHPdoc)
	 * @see Backend_Controller_Crud::listAction()
	 */
	public function listAction()
	{
		$pager = Request::post('pager' , 'array' , array());
		$filter = Request::post('filter' , 'array' , array());
		$query = Request::post('query' , 'string' , false);
		
		$dataModel = Model_Videoblock::getInstance();
		$vc = Model_Vc::getInstance();
		
		$fields = array(
				'id' , 
				'page_id' , 
				'date_created' , 
				'published' , 
				'published_version' , 
				'date_updated'
		);
		
		$data = $dataModel->getListVc($pager , $filter , $query , $fields , 'user' , 'updater');
		
		if(empty($data))
			Response::jsonSuccess(array(),array('count'=>0));
		
		$ids = array();
		$pageIds = array();
		foreach($data as $k => $v)
		{
			$ids[] = $v['id'];
			$pageIds[] = $v['page_id'];
		}
		
		$maxRevisions = $vc->getLastVersion('videoblock' , $ids);
		
		$pages = Model_Page::getInstance();
		$pagelist = $pages->getListVc(false , array(
				'id' => $pageIds
		) , false , array(
				'id' , 
				'code' , 
				'menu_title'
		));
		$pagelist = Utils::rekey('id' , $pagelist);
		
		foreach($data as $k => &$v)
		{
			if(isset($maxRevisions[$v['id']]))
				$v['last_version'] = $maxRevisions[$v['id']];
			else
				$v['last_version'] = 0;
			
			if($v['page_id'] == 0)
			{
				$v['page'] = 'default list';
				$v['page_title'] = 'Default list';
				continue;
			}
			
			if(isset($pagelist[$v['page_id']]))
			{
				$v['page'] = $pagelist[$v['page_id']]['code'] . '.html';
				$v['page_title'] = $pagelist[$v['page_id']]['menu_title'];
			}
			else
			{
				$v['page'] = '';
				$v['page_title'] = '';
			}
		
		}
		unset($v);
		
		Response::jsonSuccess($data , array(
				'count' => $dataModel->getCount($filter , $query)
		));
	}
} 